package com.imooc.service.impl;

import com.imooc.converter.OrderMaster2OrderDtoConverter;
import com.imooc.dataobject.OrderDetail;
import com.imooc.dataobject.OrderMaster;
import com.imooc.dataobject.ProductInfo;
import com.imooc.dto.CartDto;
import com.imooc.dto.OrderDto;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.PayStatusEnum;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.repository.OrderDetailRepository;
import com.imooc.repository.OrderMasterRepository;
import com.imooc.service.*;
import com.imooc.utils.KeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述: <br>
 * (订单service)
 *
 * @Author:Mr. xyb
 * @Date: 2018/5/18 17:21
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private ProductService productService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private PayService payService;

    @Autowired
    private PushMessageService pushMessageService;

    @Autowired
    private WebSocket webSocket;

    /**
     * (创建一个订单)
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public OrderDto create(OrderDto orderDto) {
        // 生成订单编号
        String orderId = KeyUtils.getUniqueKey();
        // 创建一个值为0的BigDecimal对象，一般涉及钱的值都是用BigDecimal对象保存
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        /**
         * 查询商品（数量、价格)
         * 1、遍历订单中的详细信息
         */
        for (OrderDetail orderDetail : orderDto.getOrderDetailList()) {
            // 获取订单中的某一个商品信息
            ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
            if (productInfo == null) {// 商品不存在抛出异常
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
                // throw new ResponseBankException();
            }
            /*计算订单总价*/
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);// 商品单价 * 购买数量 + 之前购买商品的价格
            orderDetail.setDetailId(KeyUtils.getUniqueKey());// 设置订单详情id
            orderDetail.setOrderId(orderId);// 设置订单id
            // 采用spring工具方法拷贝实体属性值，将商品信息设置到订单详情中
            BeanUtils.copyProperties(productInfo, orderDetail);
            // 订单详情入库
            orderDetailRepository.save(orderDetail);
        }

        /*写入订单数据库*/
        OrderMaster master = new OrderMaster();
        // 在复制属性值时，需要先把orderid设置进orderDto中，之前此对象中并没有orderid
        orderDto.setOrderId(orderId);
        BeanUtils.copyProperties(orderDto, master);// 同上，拷贝数据，赋值
        master.setOrderAmount(orderAmount);
        master.setOrderId(orderId);
        master.setOrderStatus(OrderStatusEnum.NEW.getCode());// 设置为新订单状态
        master.setPayStatus(PayStatusEnum.WAIT.getCode());// 设置为等待支付状态
        orderMasterRepository.save(master);
        /*扣库存、使用lambda表达式将订单详情中的商品id以及数量循环保存为一个购物车的list集合*/
        List<CartDto> cartDtoList = orderDto.getOrderDetailList().stream()
                .map(e -> new CartDto(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.decreaseStock(cartDtoList);// 扣库存

        /*发送websocket消息,提示有新订单创建成功*/
        webSocket.sendMessage(orderDto.getOrderId());
        return orderDto;
    }

    /**
     * (查询一个订单)
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderDto findOne(String orderId) {
        // 查询订单
        OrderMaster master = orderMasterRepository.findOne(orderId);
        if (master == null) {// 如果为空抛异常
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        // 根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailRepository.findByOrderId(orderId);
        // 如果订单详情为空，则抛异常
        if (CollectionUtils.isEmpty(orderDetails)) {
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        // 创建订单以及订单详情的对象
        OrderDto orderDto = new OrderDto();
        // 将订单对象拷贝赋值给orderDto
        BeanUtils.copyProperties(master, orderDto);
        // 将订单详情设置到orderDto
        orderDto.setOrderDetailList(orderDetails);
        return orderDto;
    }


    /**
     * (根据买家openid查询订单)
     *
     * @param buyerOpenid
     * @param pageable
     * @return
     */
    @Override
    public Page<OrderDto> findList(String buyerOpenid, Pageable pageable) {

        // (根据openid分页查询订单信息)
        Page<OrderMaster> orderMasters = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        /*转换对象*/
        List<OrderDto> orderDtoList = OrderMaster2OrderDtoConverter.convert(orderMasters.getContent());
        // 创建分页对象保存数据
        Page<OrderDto> orderDtos = new PageImpl<>(orderDtoList, pageable, orderMasters.getTotalElements());
        return orderDtos;
    }

    /**
     * (取消订单)
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public OrderDto cancel(OrderDto orderDto) {

        OrderMaster master = new OrderMaster();
        /*判断订单状态,如果订单状态不为新订单，则抛出异常*/
        if (!orderDto.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.info("【订单不正确】，orderId={},orderStatus={}", orderDto.getOrderId(), orderDto.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        /*修改订单状态*/
        orderDto.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        // 将orderDto数据拷贝到订单对象中
        BeanUtils.copyProperties(orderDto, master);
        // 保存订单数据
        OrderMaster updateResult = orderMasterRepository.save(master);

        if (updateResult == null) {
            log.error("【取消订单】更新失败，orderMaster={}", master);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        /**
         * 返回库存
         */
        if (CollectionUtils.isEmpty(orderDto.getOrderDetailList())) {// 如果订单详情为空，则抛异常
            log.error("【取消订单】订单中无商品详情,orderDto={}", orderDto);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        // 循环保存订单数据到cartDtos的list集合中
        List<CartDto> cartDtos = orderDto.getOrderDetailList().stream()
                .map(e -> new CartDto(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        // 加库存
        productService.increaseStock(cartDtos);
        /*如果已经支付，则需要退款*/
        if (orderDto.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            payService.refund(orderDto);
        }
        return orderDto;
    }

    /**
     * (完结订单)
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public OrderDto finish(OrderDto orderDto) {
        // 判断订单状态，如果订单不为新订单状态，抛异常
        if (!orderDto.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【完结订单】订单状态不正确，orderId={},orderStatus={}", orderDto.getOrderId(), orderDto.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        // 修改订单状态为完结状态
        orderDto.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        /*创建订单对象*/
        OrderMaster orderMaster = new OrderMaster();
        // 拷贝数据
        BeanUtils.copyProperties(orderDto, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);// 保存订单信息
        if (updateResult == null) {// 如果返回为空，则抛异常
            log.error("【完结订单】订单中无商品详情,orderDto={}", orderDto);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }

        // 推送微信模板消息
        pushMessageService.orderStatus(orderDto);
        return orderDto;
    }


    /**
     * (支付，修改订单支付状态)
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public OrderDto paid(OrderDto orderDto) {
        // 判断订单状态,不为新订单状态则抛异常
        if (!orderDto.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【订单支付完成】订单状态不正确，orderId={},orderStatus={}", orderDto.getOrderId(), orderDto.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        // 判断支付状态，如果不为等待支付状态则抛异常
        if (!orderDto.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("【订单支付完成】订单支付状态不正确，orderId={},orderStatus={}", orderDto.getOrderId(), orderDto.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
        // 修改支付状态为支付成功
        orderDto.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDto, orderMaster);// 拷贝数据并赋值
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);// 保存数据
        if (updateResult == null) {// 返回数据为空则抛异常
            log.error("【订单支付完成】更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDto;
    }

    /**
     * 分页查询订单list表
     *
     * @param pageable
     * @return
     */
    @Override
    public Page<OrderDto> findList(Pageable pageable) {
        // 分页查询订单列表
        Page<OrderMaster> orderMasters = orderMasterRepository.findAll(pageable);
        // 转换对象
        List<OrderDto> orderDtos = OrderMaster2OrderDtoConverter.convert(orderMasters.getContent());
        // 将转换的对象数据保存到page中
        Page<OrderDto> page = new PageImpl<>(orderDtos, pageable, orderMasters.getTotalElements());
        return page;
    }
}
